package com.edu.service.impl;

import com.edu.dao.UserDao;
import com.edu.entity.User;
import com.edu.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;

    @Override
    public User register(User user) {
        if (userDao.existsByUsername(user.getUsername())) {
            throw new RuntimeException("用户名已存在");
        }
        userDao.save(user);
        return user;
    }

    @Override
    public User login(String username, String password) {
        User user = userDao.findByUsername(username);
        if (user != null && user.getPassword().equals(password)) {
            return user;
        }
        return null;
    }

    @Override
    public User findById(Integer userId) {
        return userDao.findById(userId);
    }

    @Override
    public List<User> findAll() {
        return userDao.findAll();
    }

    @Override
    public User update(User user) {
        userDao.update(user);
        return user;
    }

    @Override
    public void delete(Integer userId) {
        userDao.delete(userId);
    }

    @Override
    public boolean checkUsernameExists(String username) {
        return userDao.existsByUsername(username);
    }

    @Override
    public void changePassword(Integer userId, String newPassword) {
        User user = userDao.findById(userId);
        if (user != null) {
            user.setPassword(newPassword);
            userDao.update(user);
        }
    }
}